#ifndef _GC_COMMON_URL_READER_H_
#define _GC_COMMON_URL_READER_H_

#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include "config.h"
#include "list.h"

typedef struct {
	size_t len;
	char * data;
} gc_stream_t;

static size_t gc_stream_write(void *ptr, size_t size, size_t nmemb,	FILE *stream) {
	gc_stream_t * s = (gc_stream_t *) stream;

	size_t len = size * nmemb;
	s->data = s->data == NULL ? malloc(len + 1) : realloc(s->data, s->len + len + 1);
	memcpy(s->data + s->len, ptr, len);
	s->len += len;
	s->data[s->len] = '\0';

	return len;
}

gc_list_t * gc_get_config_by_url(const gc_config_t * config) {
	char url[1024] = {0};

	if(config->src != GC_SRC_URL) {
		fprintf(stderr, "%s:%d: gc_config_t::src is not url\n", __FILE__, __LINE__);
		return NULL;
	}
	snprintf(url, sizeof(url), "%s%sgroup=%s", config->data,
			(strchr(config->data, '?') == NULL ? "?" : "&"), config->group);

	gc_stream_t * stream = malloc(sizeof(gc_stream_t));
	memset(stream, 0, sizeof(gc_stream_t));

	CURL * curl  = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, gc_stream_write);
	curl_easy_setopt(curl, CURLOPT_FILE, stream);
	CURLcode res = curl_easy_perform(curl);

	if(res != CURLE_OK) {
		fprintf(stderr, "%s:%d fetch %s failed with message: %s\n", 
				__FILE__, __LINE__, url, curl_easy_strerror(res));
		curl_easy_cleanup(curl);
		return NULL;
	}
	long code = 0;
	if(curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code) != CURLE_OK
			|| code != 200 || stream->len == 0) {
		fprintf(stderr, "%s:%d reponse_code is %d when fetching %s, data len is %lu\n", 
				__FILE__, __LINE__, (int) code, (char*)url, stream->len);
		curl_easy_cleanup(curl);
		return NULL;
	}
	curl_easy_cleanup(curl);

	json_object * json = json_tokener_parse(stream->data);

	gc_list_t * list = gc_convert_json_object_to_list(json);

	if(json != NULL) {
		json_object_put(json);
	}

	return list;
}


#endif
